package com.xuequ.answerme.settings;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.xuequ.answerme.R;
import com.xuequ.answerme.beans.UserBean;
import com.xuequ.answerme.manager.UserManager;
import com.xuequ.answerme.tools.FileTools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import de.hdodenhof.circleimageview.CircleImageView;
import me.drakeet.materialdialog.MaterialDialog;

/**
 * Created by shijie on 2015/11/8.
 */
public class PersonalInfoActivity extends AppCompatActivity {


    private static final String IMAGE_FILE_NAME = "header.jpg";

    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int IMAGE_REQUEST_CODE_KITKAT = 4;

    private UserBean userBean;
    private UserManager userManager;

    private Toolbar toolbar;

    private CircleImageView avatarImg;
    private Button selectButton;
    private Button photoButton;
    private MaterialDialog avatarMaterialDialog;
    private View avatarView;
    private CardView avatarCard;


    private CardView usernameCard;
    private TextView usernameText;
    private MaterialDialog usernameMaterialDialog;
    private View usernameView;
    private TextView cancelUsernameText;
    private TextView okUsernameText;
    private TextInputLayout usernameInputText;

    private CardView signatureCard;
    private TextView signatureText;
    private MaterialDialog signatureMaterialDialog;
    private View signatureView;
    private TextView cancelSignatureText;
    private TextView okSignatureText;
    private TextInputLayout signatureInputText;

    private Intent intent = getIntent();
    private Bundle bundle;
    private UserBean userChangedBean;
    private boolean infoIsChanged = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);
        initViews();
    }

    private void initViews() {

        if (userManager == null) {
            userManager = new UserManager();
        }

        userBean = BmobUser.getCurrentUser(PersonalInfoActivity.this, UserBean.class);
        userChangedBean = new UserBean();

        bundle = new Bundle();

        toolbar = (Toolbar) findViewById(R.id.personal_info_tool_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        avatarCard = (CardView) findViewById(R.id.personal_info_avatar_card);
        avatarCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAvatarDialog();
            }
        });
        avatarImg = (CircleImageView) findViewById(R.id.personal_info_avatar_img);
        Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + FileTools.AVATAR_NAME);
        avatarImg.setImageBitmap(bitmap);

        usernameCard = (CardView) findViewById(R.id.personal_info_username_card);
        usernameText = (TextView) findViewById(R.id.personal_info_username_text);
        usernameText.setText(userBean.getUsername());
        usernameCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUsernameDialog();
            }
        });

        signatureCard = (CardView) findViewById(R.id.personal_info_signature_card);
        signatureText = (TextView) findViewById(R.id.personal_info_signature_text);
        if(!TextUtils.isEmpty(userBean.getSignature())){
            signatureText.setText(userBean.getSignature());
        }
        signatureCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSignatureDialog();
            }
        });

    }

    /**
     * 显示更改签名框
     */
    private void showSignatureDialog() {
        signatureView = View.inflate(this, R.layout.settings_signature_change_layout, null);
        signatureInputText = (TextInputLayout) signatureView.findViewById(R.id.settings_change_signature_textInput);

        okSignatureText = (TextView) signatureView.findViewById(R.id.settings_change_signature_ok_text);
        okSignatureText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String newSignature = signatureInputText.getEditText().getText().toString();
                if (!TextUtils.isEmpty(newSignature)) {
                    okSignatureText.setClickable(false);
                    userManager.updateSignature(PersonalInfoActivity.this, newSignature, new UserManager.UpdateUserInfoListener() {
                        @Override
                        public void updateUserInfoOnSuccess() {
                            signatureText.setText(newSignature);
                            infoIsChanged = true;
                            userChangedBean.setSignature(newSignature);
                            signatureMaterialDialog.dismiss();
                            okSignatureText.setClickable(true);
                        }

                        @Override
                        public void updateUserInfoOnFailure(String failureMsg) {
                            okSignatureText.setClickable(true);
                            Log.i("update signature","failure "+failureMsg);
                        }
                    });
                }
            }
        });

        cancelSignatureText = (TextView) signatureView.findViewById(R.id.settings_change_signature_cancel_text);
        cancelSignatureText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signatureMaterialDialog.dismiss();
            }
        });

        signatureMaterialDialog = new MaterialDialog(this).setView(signatureView);
        signatureMaterialDialog.show();

    }

    /**
     * 显示更改用户名框
     */
    private void showUsernameDialog() {

        usernameView = View.inflate(this, R.layout.settings_username_change_layout, null);

        usernameInputText = (TextInputLayout) usernameView.findViewById(R.id.settings_change_username_textInput);

        okUsernameText = (TextView) usernameView.findViewById(R.id.settings_change_username_ok_text);
        okUsernameText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String newName = usernameInputText.getEditText().getText().toString();
                if (!TextUtils.isEmpty(newName)) {
                    okUsernameText.setClickable(false);
                    userManager.updateUsername(PersonalInfoActivity.this, newName, new UserManager.UpdateUserInfoListener() {
                        @Override
                        public void updateUserInfoOnSuccess() {
                            usernameText.setText(newName);
                            infoIsChanged = true;
                            userChangedBean.setUsername(newName);
                            usernameMaterialDialog.dismiss();
                            okUsernameText.setClickable(true);
                        }

                        @Override
                        public void updateUserInfoOnFailure(String failureMsg) {
                            okUsernameText.setClickable(true);
                            Log.i("update signature", "failure " + failureMsg);
                        }
                    });
                }
            }
        });

        cancelUsernameText = (TextView) usernameView.findViewById(R.id.settings_change_username_cancel_text);
        cancelUsernameText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                usernameMaterialDialog.dismiss();
            }
        });

        usernameMaterialDialog = new MaterialDialog(this).setView(usernameView);
        usernameMaterialDialog.show();

    }

    /**
     * 显示头像选择框
     */
    private void showAvatarDialog() {

        avatarView = View.inflate(this, R.layout.settings_avatar_change_layout, null);
        photoButton = (Button) avatarView.findViewById(R.id.setting_change_avatar_photos_button);
        photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //下面这句指定调用相机拍照后的照片存储的路径
                takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
                startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
                avatarMaterialDialog.dismiss();
            }
        });

        selectButton = (Button) avatarView.findViewById(R.id.setting_change_avatar_gallery_button);
        selectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                galleryIntent.setType("image/*");
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE_KITKAT);
                } else {
                    startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
                }
                avatarMaterialDialog.dismiss();
            }
        });

        avatarMaterialDialog = new MaterialDialog(this).setView(avatarView);
        avatarMaterialDialog.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    Log.i("path", "path------------->" + data.getData().toString());
                    break;
                case RESIZE_REQUEST_CODE:
                    if (data != null) {
                        showResizeImage(data);
                    }
                    break;
                case IMAGE_REQUEST_CODE_KITKAT:
                    Log.i("uri", "uri------------------->" + data.getData());
                    Log.i("uri", "path------------------->" + getImageAbsolutePath(this, data.getData()));
                    resizeImage(Uri.fromFile(new File(getImageAbsolutePath(this, data.getData()))));
                    break;
                case CAMERA_REQUEST_CODE:
                    if (isSdcardExisting()) {
                        resizeImage(getImageUri());
                    } else {
                        Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean isSdcardExisting() {
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public void resizeImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 1080);
        intent.putExtra("outputY", 1080);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }

    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param context
     * @param imageUri
     */
    @TargetApi(19)
    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    private void showResizeImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            saveBitmap(photo);
            uploadAvatar(drawable);
        }
    }

    private void uploadAvatar(final Drawable drawable) {
        File avatar = new File(Environment.getExternalStorageDirectory() + "/" + FileTools.AVATAR_NAME);
        Log.i("avatar name", "------------------------>" + avatar.length());
        final BmobFile file = new BmobFile(avatar);
        file.upload(this, new UploadFileListener() {
            @Override
            public void onSuccess() {
                final UserBean userBean = new UserBean();
                userBean.setAvatar(file);
                userBean.update(PersonalInfoActivity.this, BmobUser.getCurrentUser(PersonalInfoActivity.this, UserBean.class).getObjectId(), new UpdateListener() {
                    @Override
                    public void onSuccess() {
                        Log.i("avatar", "--------------------------------->success" + file.getFileUrl(PersonalInfoActivity.this));
                        infoIsChanged = true;
                        Log.i("avatar filename", "-->" + file.getFilename());
                        userBean.setAvatar(file);
                        avatarImg.setImageDrawable(drawable);
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Log.i("avatar", "--------------------------------->failure update " + s);
                    }
                });
            }

            @Override
            public void onFailure(int i, String s) {
                Log.i("avatar", "--------------------------------->failure upload " + s);
            }
        });

    }

    public void saveBitmap(Bitmap bm) {
        File f = new File(Environment.getExternalStorageDirectory(), FileTools.AVATAR_NAME);
        if (f.exists()) {//如果文件存在就换个名字存
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private Uri getImageUri() {
        return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME));
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
